/**
 * Copyright (C) 2012-2013 jumei, Inc.
 * NettyUtils.java
 * 2015年6月19日
 */
package org.goface.rpc.io;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.handler.codec.serialization.ClassResolver;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

import com.example.tutorial.AddressBookProtos.Person;

/**
 *
 * @author jm110
 */
public class NettyUtils {

    public static void addProtocBufCodec(Channel ch, ChannelHandler handler) {
        ch.pipeline().addLast(new ProtobufVarint32FrameDecoder());
        ch.pipeline().addLast(new ProtobufDecoder(Person.getDefaultInstance()));
        // encoded
        ch.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());
        ch.pipeline().addLast(new ProtobufEncoder());
        ch.pipeline().addLast(handler);
    }

    public static void addJavaSerialiseCodec(Channel ch, ChannelHandler handler) {
        ClassResolver classResolver = ClassResolvers.cacheDisabled(Thread.currentThread().getContextClassLoader());
        ch.pipeline().addLast(new ObjectDecoder(100000, classResolver));
        ch.pipeline().addLast(new ObjectEncoder());
        ch.pipeline().addLast(handler);

    }

}
